﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

namespace Web.Infrastructure.Extensions
{
    public static class EnumExtensions
    {
        public static HtmlString EnumToKeysMap<T>(this HtmlHelper helper) where T : struct
        {
            object enumeration = Activator.CreateInstance(typeof (T));
            Dictionary<string, int> enums =
                Enum.GetValues(typeof (T)).Cast<int>().ToDictionary(x => Enum.GetName(typeof (T), x), y => y);

            return new HtmlString(Json.Encode(enums));
        }

        public static HtmlString EnumToValuesMap<T>(this HtmlHelper helper) where T : struct
        {
            object enumeration = Activator.CreateInstance(typeof (T));
            Dictionary<string, string> enums =
                Enum.GetValues(typeof (T))
                    .Cast<int>()
                    .ToDictionary(x => x.ToString(CultureInfo.InvariantCulture), y => Enum.GetName(typeof (T), y));

            return new HtmlString(Json.Encode(enums));
        }

        public static Dictionary<string, string> EnumToLocalizedDictionary(this Enum sourceEnum, bool includeNullEntry)
        {
            var dictionary = new Dictionary<string, string>();
            if (includeNullEntry) dictionary.Add("","");
            foreach (object v in Enum.GetValues(sourceEnum.GetType()))
            {
                dictionary.Add(((int)v).ToString(), ((Enum)v).ToString());
            }

            return dictionary;
        }

        public static Dictionary<string, string> EnumToDictionary(this Enum sourceEnum, bool includeNullEntry)
        {
            var dictionary = new Dictionary<string, string>();
            if (includeNullEntry) dictionary.Add("", "");
            foreach (object v in Enum.GetValues(sourceEnum.GetType()))
            {
                dictionary.Add(((int)v).ToString(), v.ToString());
            }

            return dictionary;
        }
    }
}